Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Val err details #12

Merged
merged 19 commits into from
Jul 9, 2021
Merged

Val err details #12

merged 19 commits into from
Jul 9, 2021

Conversation

bheylin
Copy link
Contributor

@bheylin bheylin commented Jul 5, 2021

I've added more detail to the ValidationError.

  • ValidationError::source_type field stores the name of the source type
  • ValidationError::message stores an error message.
  • ValidationError::new::<T>(message) fills in the source_type name based on T and stores the message.
  • I've removed PartialEq (you should always pair PartialEq and Eq) as it was only being used for equality comparisons in the integration tests. Using assert_matches! allows you to avoid equality tests as the pattern matching system does not use equality tests.

ObsceneGiraffe added 2 commits July 5, 2021 18:31
- ValidationError should have more detail.
- ValidationError::message should maybe have a String so people can use
format! to generate the messages.
@bheylin
Copy link
Contributor Author

bheylin commented Jul 5, 2021

Looks like my merge went completely wrong.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 5, 2021

I reverted the mis-merge of the master branch.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 5, 2021

Maybe this closes #5 ?

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

It looks like you're deleting .github/workflows/rust.yml

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

Why not use assert!(matches!(...)) instead of assert_matches!(...)? I kind of like the first variant more. And it needs no dependency.

prae_macro/src/lib.rs Outdated Show resolved Hide resolved
@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

I wonder if the fields of the ValidationError should be public. Perhaps we should make it private and use only for the message?

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

I also think we should add value: Option<T> field. It could be used by Guarded<_>::new to return provided value in case of fail. Reference:
https://github.com/PabloMansanet/tightness/blob/master/src/core.rs#L95

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

Although all of this is starting to be a bit messy. Looking from a UX point of view, the error should say something like failed to create Username from " ": provided value is invalid. For this we need 1) the name of the source type 2) provided value. In case of Guarded<_>::new it should also probably return provided value back (as it owns it)....

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

Another idea: we can create two separate default errors for construction/mutation:

  1. ConstructionError<T>(T). Possible message: failed to construct Username(" "): provided value is invalid. It should also contain the value, so the user can take the ownership back.
  2. MutationError<T>. Possible message: failed to mutate Username("valid name") to Username(" "): provided value is invalid.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 6, 2021

It looks like you're deleting .github/workflows/rust.yml

I'll sort this out later today, I'm just starting my day here 😉

Why not use assert!(matches!(...)) instead of assert_matches!(...)? I kind of like the first variant more. And it needs no dependency.

assert_matches! outputs a clearer assertion message, assert!(matches!(...)) just outputs that the match fails.

I wonder if the fields of the ValidationError should be public. Perhaps we should make it private and use only for the message?

I was wondering the same. I see this code as a first draft. In the case of this type, making the fields private makes sense as who knows how we want to represent the source_type in future. I also think the we may want to make the message field type String so that it's plays better with format! and constructing messages in general.

I also think we should add value: Option<T> field. It could be used by Guarded<_>::new to return provided value in case of fail. Reference:
https://github.com/PabloMansanet/tightness/blob/master/src/core.rs#L95

I'll take a look at your proposed solutions later on. But one way or the other having access to the input value is critical for a decent error message.

@teenjuna
Copy link
Owner

teenjuna commented Jul 6, 2021

I'll sort this out later today, I'm just starting my day here 😉

Of course :)

assert_matches! outputs a clearer assertion message, assert!(matches!(...)) just outputs that the match fails.

Fair

I was wondering the same. I see this code as a first draft. In the case of this type, making the fields private makes sense as who knows how we want to represent the source_type in future. I also think the we may want to make the message field type String so that it's plays better with format! and constructing messages in general.

I thought about the String too. We need to think about the use-cases

@teenjuna teenjuna marked this pull request as draft July 6, 2021 09:47
@bheylin
Copy link
Contributor Author

bheylin commented Jul 7, 2021

Another idea: we can create two separate default errors for construction/mutation:

1. `ConstructionError<T>(T)`. Possible message: `failed to construct Username("  "): provided value is invalid`. It should also contain the value, so the user can take the ownership back.

2. `MutationError<T>`. Possible message: `failed to mutate Username("valid name") to Username("  "): provided value is invalid`.

I like the idea of separate errors for the separate actions. I'll take a look at adding the value now.

- The message field is removed as there is no need for custom error
  messages yet.
- The type alias is passed given to the Error so it can print it.
README.md Outdated
@@ -47,12 +47,12 @@ let mut u = Username::new(" valid name \n\n").unwrap();
assert_eq!(u.get(), "valid name"); // now we're talking!

// This also works for mutations:
assert!(matches!(u.try_mutate(|u| *u = " ".to_owned()), Err(prae::ValidationError)));
assert!(matches!(u.try_mutate(|u| *u = " ".to_owned()), Err(prae::ConstructionError<String>)));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't it be MutationError<String>?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea I didn't add the mutation error yet

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to argue that the generic bound E should be removed. See the comment below.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 7, 2021

With the current arch of the validate fn and the ConstructionError the usage is quite clunky if you don't want to make a custom error.

prae::define! {
        pub Username: String
        validate |u| -> Option<prae::ConstructionError::<String>> {
            if u.is_empty() {
                Some(prae::ConstructionError::new("Username", u.clone()))
            } else {
                None
            }
        }
    }

I think that the validate closure should return a Result<(), Err> as that is idiomatic and means that the ? operator can be used in the closure.

use prae;

#[derive(Debug)]
pub struct UsernameError;

prae::define! {
    pub Username: String
    validate |u| -> Result<(), UsernameError> {
        if u.is_empty() {
            Err(UsernameError{})
        } else {
            Ok(())
        }
    }
}

I think prae::Guarded::new should always return a ConstructionError.
The signature should change to pub fn new<V: Into<T>>(v: V) -> Result<Self, ConstructionError> {.
When the user wants to use a custom error it's simply made the std::error::Error::source of ConstructionError.

I would like to capture errors returned from the validate closure of type String and concat that onto the existing ConstructionError message.

lazy_static! {
    static ref SOME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9 \-]{1,100}$").unwrap();
}

prae::define! {
    pub Username: String
    validate |u| -> Result<(), String> {
        if SOME_REGEX.is_match(s) {
            Ok(())
        } else {
            Err(format!("match failed for regex {}", regex))
        }
    }
}

That would generate an error:

failed to create Username from \"\": provided value is invalid
match failed for regex ^[a-zA-Z0-9 \-]{1,100}$

un.try_mutate(|u| *u = "".to_owned()).unwrap_err(),
prae::ValidationError
);
let _error: prae::ConstructionError<String> = un.try_mutate(|u| *u = "".to_owned()).unwrap_err();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not assert_matches!?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll put assert_matches back in. I was having trouble getting the match to compile using the generic param, but all I need is a turbo fish.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The assert_matches! are restored.

prae/src/core.rs Outdated
T: fmt::Debug
{
/// The name of the type where this ConstructionError originated.
guarded_type_name: String,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure it should be String since we know the type during compile time

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to print the alias, how would I store that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type is quite a mouthful 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but.. it could be a &'static str...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch, the change is pushed.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I meant the &'static str, sorry for not being clear

@teenjuna
Copy link
Owner

teenjuna commented Jul 7, 2021

I think that the validate closure should return a Result<(), Err> as that is idiomatic and means that the ? operator can be used in the closure.

Good point. I agree.

I think prae::Guarded::new should always return a ConstructionError.
The signature should change to pub fn new<V: Into<T>>(v: V) -> Result<Self, ConstructionError> {.
When the user wants to use a custom error it's simply made the std::error::Error::source of ConstructionError.

I don't think it should. The reason why it's generic is because it's meant to be as flexible as possible and return any error. The ConstructionError and MutationError are just convenient default errors. Anyway, it's late in my area, so I'm gonna read your proposal again in the morning.

Also, I have an idea about possible design that will allow user to return custom messages, but I didn't finish it so I also do it a bit later (haven't much time today :)). Anyway, thank you for your help, we'll finish it soon :)

@bheylin
Copy link
Contributor Author

bheylin commented Jul 7, 2021

I don't think it should. The reason why it's generic is because it's meant to be as flexible as possible and return any error. The ConstructionError and MutationError are just convenient default errors. Anyway, it's late in my area, so I'm gonna read your proposal again in the morning.

All good, get some rest 😉 We'll talk about it soon.

@teenjuna
Copy link
Owner

teenjuna commented Jul 8, 2021

So, I looked at it and it seems to me that bringing ConstructionError and MutationError is just impossible with the current code. I don't want to break the usage of the validate with Error::source as its usage will be inconvenient.

Possible solution will be to split the Guarded into EnsureGuarded and ValidateGuarded (as it was in the beginning, if you look at commits history), where EnsureGuarded will explicitly return ConstructionError and MutationError, but it will complicate both the API and the implementation of the macro.

I think right now we can just revert to the HEAD and add information about the type to the ValidatationError, like so:

pub struct ValidationError<T> {
    _ty: PhantomData<T>,
}

impl<T> fmt::Debug for ValidationError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "failed to construct/mutate {}: provided value is not valid",
            std::any::type_name::<T>()
        )
    }
}

impl<T> fmt::Display for ValidationError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Self as fmt::Debug>::fmt(self, f)
    }
}

impl<T> std::error::Error for ValidationError<T> {}

And change the tests to use assert_matches instead of directly comparing it.

I propose to focus on another topics right now and return to this later. The fact that a user will see the message failed to construct/mutate Username: provided value is not valid is nice for now.

What do you think?

@teenjuna
Copy link
Owner

teenjuna commented Jul 8, 2021

Although we could probably define ConstructionError<E> and MutationError<E> that are generic over some error E, which can be custom error defined in validate, or just a &'static str for the default error with ensure. In case of custom error, these errors can implement Into<E>, which should allow to use ? to cast them with the Result<..., E> (not sure, didn't test it). Then we can use them in all cases

- There was a plan to have two errors, one for Construction and another
for Mutation. This is not going ahead due to it requiring major arch
changes.
@bheylin
Copy link
Contributor Author

bheylin commented Jul 9, 2021

So, I looked at it and it seems to me that bringing ConstructionError and MutationError is just impossible with the current code. I don't want to break the usage of the validate with Error::source as its usage will be inconvenient.

Agreed for the increase in complexity doesn't justify the value of having a MutationErrorthat provides the value you're mutating. I would argue that knowing the value you're try to mutate to is all you really care about anyway.

I'm happy with the implementation as it is, a single ValidationError that allows me to see the alias name and the value that failed to validate.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 9, 2021

Although we could probably define ConstructionError<E> and MutationError<E> that are generic over some error E, which can be custom error defined in validate, or just a &'static str for the default error with ensure. In case of custom error, these errors can implement Into<E>, which should allow to use ? to cast them with the Result<..., E> (not sure, didn't test it). Then we can use them in all cases

I think this is also needless complexity for the value of having two Errors types. Let's keep it to one Error type until the need arises to make two.

@bheylin
Copy link
Contributor Author

bheylin commented Jul 9, 2021

I would like to implement validate returning a Result<(), E> in a separate branch so that this change is just enough to fix #5.

@teenjuna teenjuna marked this pull request as ready for review July 9, 2021 11:09
Comment on lines 80 to 85
#[cfg(test)]
mod test_deps {
use assert_matches as _;
use serde as _;
use serde_json as _;
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Btw, why is this necessary?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean the whole test_deps business

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the lint to warn about unused crate dependencies.

#![warn(unused_crate_dependencies)]

But it give's false positives when buliding the separate integration test binaries.

❯ cargo test
   Compiling prae_macro v0.2.1 (/home/brianh/Projects/third_party/prae/prae_macro)
   Compiling prae v0.4.5 (/home/brianh/Projects/third_party/prae/prae)
warning: external crate `assert_matches` unused in `prae`: remove the dependency or add `use assert_matches as _;`
   |
note: the lint level is defined here
  --> prae/src/lib.rs:71:9
   |
71 | #![warn(unused_crate_dependencies)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^
   = help: remove unnecessary dependency `assert_matches`

warning: external crate `serde` unused in `prae`: remove the dependency or add `use serde as _;`
  |
  = help: remove unnecessary dependency `serde`

warning: external crate `serde_json` unused in `prae`: remove the dependency or add `use serde_json as _;`
  |
  = help: remove unnecessary dependency `serde_json`

warning: 3 warnings emitted

    Finished test [unoptimized + debuginfo] target(s) in 0.73s
     Running unittests (target/debug/deps/prae-dc495198ddde61f3)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, now I get it. I'll add a comment referencing the related issue: rust-lang/rust#57274

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 😉

let f: fn(&Self::Target) -> bool = #closure;
if f(v) { None } else { Some(prae::ValidationError) }
if f(v) { None } else { Some(prae::ValidationError::<#ty>::new(stringify!(#ident), v.clone()) ) }
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the type is not clone? In this case the user will use Guarded::mutate instead of Guarded::try_mutate, but they both use validate

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, exactly. The following code works on HEAD but not on this branch:

#[derive(Debug)]
struct User {
    name: String,
}

prae::define! {
    ValidUser: User
    ensure |u: &User| !u.name.is_empty()
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's either clone, copy or have the error manage reference lifetimes. I would like to avoid having lifetimes as that constraint will leak into the users code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can add a nicer message though, instead of a compile error emanating from the proc macro?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it's also can't be done with the current code. Introducing ConstructionError<E> and MutationError<E> should solve the issue, since we'll be able to insert the value: T inside Guarded::new and Guarded::try_mutate

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see a way around cloning, as we have to clone at some point so the error can store the value, or.... you convert the value to a string which requires T: Debug or T: DIsplay.

Requiring Clone on a type is a reasonable expectation given that it's trivial to implement and it's the exception that you see types that are not clone-able.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest commit removes the value.

Copy link
Owner

@teenjuna teenjuna Jul 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making it T: Debug and turning it into string is a reasonable workaround! But expecting the value to be always Clone is a no go, since the library must be available for as many use cases as possible. Sometimes making your value !Clone is a design choice, and we must tolerate this.

Do you want to add str_value: String or should I do it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can do it. I'll update the non_clone test too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ValidationError::value is reinstated as a String, changes are pushed.

@teenjuna
Copy link
Owner

teenjuna commented Jul 9, 2021

Perfect!

@teenjuna teenjuna merged commit 427c71e into teenjuna:master Jul 9, 2021
@bheylin bheylin deleted the val_err_details branch July 12, 2021 16:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants